from typing import Any, Dict, Optional, Union, Generic, TypeVar
from enum import Enum
import time
from pydantic import BaseModel, Field
from datetime import datetime


class ResponseCode(Enum):
    """响应状态码枚举类"""
    SUCCESS = 200  # 成功
    PARAM_ERROR = 400  # 参数错误
    UNAUTHORIZED = 401  # 未授权
    FORBIDDEN = 403  # 禁止访问
    NOT_FOUND = 404  # 资源不存在
    SERVER_ERROR = 500  # 服务器错误
    SERVICE_UNAVAILABLE = 503  # 服务不可用


# 用于泛型参数的类型变量
T = TypeVar('T')

class ResponseResult(BaseModel, Generic[T]):
    """统一响应结果模型"""
    code: int = Field(200, description="状态码")
    message: str = Field("操作成功", description="响应消息")
    data: Optional[T] = Field(None, description="响应数据")
    timestamp: int = Field(default_factory=lambda: int(time.time() * 1000), description="时间戳")

    class Config:
        """Pydantic配置"""
        from_attributes = True  # 允许从ORM模型创建
    
    @classmethod
    def success(cls, data: Any = None, message: str = "操作成功") -> Dict[str, Any]:
        """
        成功响应
        
        Args:
            data: 响应数据
            message: 响应消息
            
        Returns:
            Dict: 统一格式的响应字典
        """
        return {
            "code": ResponseCode.SUCCESS.value,
            "message": message,
            "data": data,
            "timestamp": int(time.time() * 1000)
        }
    
    @classmethod
    def error(cls, code: Union[int, ResponseCode], message: str, data: Any = None) -> Dict[str, Any]:
        """
        错误响应
        
        Args:
            code: 错误码
            message: 错误消息
            data: 额外数据
            
        Returns:
            Dict: 统一格式的响应字典
        """
        if isinstance(code, ResponseCode):
            code = code.value
            
        return {
            "code": code,
            "message": message,
            "data": data,
            "timestamp": int(time.time() * 1000)
        }
    
    @classmethod
    def param_error(cls, message: str = "参数错误", data: Any = None) -> Dict[str, Any]:
        """参数错误响应"""
        return cls.error(ResponseCode.PARAM_ERROR, message, data)
    
    @classmethod
    def unauthorized(cls, message: str = "未授权", data: Any = None) -> Dict[str, Any]:
        """未授权响应"""
        return cls.error(ResponseCode.UNAUTHORIZED, message, data)
    
    @classmethod
    def forbidden(cls, message: str = "禁止访问", data: Any = None) -> Dict[str, Any]:
        """禁止访问响应"""
        return cls.error(ResponseCode.FORBIDDEN, message, data)
    
    @classmethod
    def not_found(cls, message: str = "资源不存在", data: Any = None) -> Dict[str, Any]:
        """资源不存在响应"""
        return cls.error(ResponseCode.NOT_FOUND, message, data)
    
    @classmethod
    def server_error(cls, message: str = "服务器错误", data: Any = None) -> Dict[str, Any]:
        """服务器错误响应"""
        return cls.error(ResponseCode.SERVER_ERROR, message, data)
    
    @classmethod
    def service_unavailable(cls, message: str = "服务不可用", data: Any = None) -> Dict[str, Any]:
        """服务不可用响应"""
        return cls.error(ResponseCode.SERVICE_UNAVAILABLE, message, data) 